package net.acnull.arpg.rpg.skill.skills;

import net.acnull.arpg.Main;
import net.acnull.arpg.effect.Light;
import net.acnull.arpg.rpg.AbstractRPG;
import net.acnull.arpg.rpg.RPGManager;
import net.acnull.arpg.rpg.skill.Skill;
import net.acnull.arpg.rpg.skill.Skillable;
import org.bukkit.Bukkit;
import org.bukkit.Particle;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;

import java.util.Random;

public class CritSkill implements Skill {

    static{
        Bukkit.getPluginManager().registerEvents(new AttackListener(),Main.getPlugin(Main.class));
    }

    private final float time;
    private final int t;
    private final int level;

    public CritSkill(float time,int t,int level){
        this.time=time;
        this.t=t;
        this.level=level;
    }

    @Override
    public void onClick(Player player,Action action) {

    }

    @Override
    public void onDamage(LivingEntity entity) {

    }

    static class AttackListener implements Listener{
        @EventHandler
        public void onAttack(EntityDamageByEntityEvent event){
            if(!(event.getDamager() instanceof LivingEntity)||!(event.getEntity() instanceof LivingEntity)){
                return;
            }
            LivingEntity attacker=(LivingEntity)event.getDamager();
            LivingEntity entity= (LivingEntity) event.getEntity();
            ItemStack item=attacker.getEquipment().getItemInMainHand();
            if(item!=null&&item.hasItemMeta()&&item.getItemMeta().hasLore()){
                AbstractRPG rpg= RPGManager.getInstance().getRPGByFirstLore(item.getItemMeta().getLore().get(0));
                if(rpg instanceof Skillable){
                    Skill skill=((Skillable)rpg).getSkill();
                    if(skill instanceof CritSkill){
                        new Light(entity.getLocation(), 2, ((CritSkill) skill).level).create();
                        if(new Random().nextInt(100)> ((CritSkill) skill).t){
                            return;
                        }
                        event.setDamage(event.getDamage()* ((CritSkill) skill).time);
                        entity.getWorld().spawnParticle(Particle.SWEEP_ATTACK,entity.getLocation(),5);
                        entity.getWorld().spawnParticle(Particle.CLOUD,entity.getLocation(),1);
                    }
                }
            }
        }
    }
}
